package com.zhihaoliang.baseframe.viewmodel;

import android.app.Application;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.arch.core.util.Function;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.SavedStateHandle;
import androidx.lifecycle.Transformations;

import com.zhihaoliang.baseframe.BasicApp;
import com.zhihaoliang.baseframe.db.DataRepository;
import com.zhihaoliang.baseframe.db.entity.ProductEntity;

import java.util.List;

/**
 * 创建日期：2020-02-29
 * 描述:产品列表车ViewModel
 * 作者:支豪亮
 */
public class ProductListViewModel extends AndroidViewModel {
    public static final String QUERY_KEY = "QUERY";

    public final SavedStateHandle mSaveStateHandle;
    public final DataRepository mRepository;
    private final LiveData<List<ProductEntity>> mProducts;

    public ProductListViewModel(@NonNull Application application, @NonNull SavedStateHandle savedStateHandle) {
        super(application);

        mSaveStateHandle = savedStateHandle;
        mRepository = ((BasicApp) getApplication()).getRepository();

        //使用savedStateHandle.getLiveData（）作为switchMap的输入，
        //允许我们重新计算从数据存储库中获取的LiveData
        //基于用户输入的查询
        mProducts = Transformations.switchMap(
                savedStateHandle.getLiveData(QUERY_KEY, null),
                (Function<CharSequence, LiveData<List<ProductEntity>>>) query -> {
                    if (TextUtils.isEmpty(query)) {
                        return mRepository.getProducts();
                    }
                    return mRepository.searchProduct("*" + query + "*");
                }
        );
    }

    public void setQuery(CharSequence query) {
        mSaveStateHandle.set(QUERY_KEY, query);
    }

    public LiveData<List<ProductEntity>> getmProducts() {
        return mProducts;
    }
}
